package com.jsyl.lwbk.business.service.education.impl;

import com.jsyl.lwbk.business.domain.education.*;
import com.jsyl.lwbk.business.dto.EvaluateInfoDTO;
import com.jsyl.lwbk.business.dto.education.*;
import com.jsyl.lwbk.business.mapper.education.ChildCourseMapper;
import com.jsyl.lwbk.business.mapper.education.CourseChildMapper;
import com.jsyl.lwbk.business.service.education.IChildCourseService;
import com.jsyl.lwbk.business.service.education.IChildTrainingProgramService;
import com.jsyl.lwbk.business.service.education.ITrainingProgramChildRecordService;
import com.jsyl.lwbk.business.vo.education.ChildCourseVO;
import com.jsyl.lwbk.common.exception.BusinessException;
import com.jsyl.lwbk.common.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xs
 * @date 2020-11-02 16:18
 * @desc
 **/
@Service
public class ChildCourseServiceImpl implements IChildCourseService {

    @Autowired
    private ChildCourseMapper childCourseMapper;

    @Autowired
    private CourseChildMapper courseChildMapper;

    @Autowired
    private ITrainingProgramChildRecordService iTrainingProgramChildRecordService;

    @Autowired
    private IChildTrainingProgramService childTrainingProgramService;

    @Override
    public List<CourseChild> listNextmonthCourseChild() {
        List<CourseChild> courseChildren = new ArrayList<CourseChild>();
        ChildCourseExample example = new ChildCourseExample();
        example.createCriteria().andDayDateBetween(DateUtils.getMonthBegin(DateUtils.getStrTime(DateUtils.getNextMonth())),DateUtils.getMonthEnd(DateUtils.getStrTime(DateUtils.getNextMonth())));
        List<ChildCourse> childCourses = childCourseMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(childCourses)){
            for(ChildCourse childCourse:childCourses){
                CourseChildExample courseChildExample = new CourseChildExample();
                courseChildExample.createCriteria().andCourseIdEqualTo(childCourse.getId());
                List<CourseChild> courseChildList = courseChildMapper.selectByExample(courseChildExample);
                if(!CollectionUtils.isEmpty(courseChildList)){
                    for(CourseChild courseChild:courseChildList){
                        courseChild.setCenterId(childCourse.getCenterId());
                        courseChild.setProjectType(childCourse.getProjectType());
                    }
                    courseChildren.addAll(courseChildList);
                }
            }
        }
        courseChildren = removeDuplicateChild(courseChildren);
        return courseChildren;
    }

    @Override
    public List<CourseChild> listCurrentmonthCourseChild() {
        List<CourseChild> courseChildren = new ArrayList<CourseChild>();
        ChildCourseExample example = new ChildCourseExample();
//        example.createCriteria().andDayDateBetween(DateUtils.getDate(),DateUtils.parseDateToStr("yyyy-MM-dd",DateUtils.addDays(DateUtils.getNowDate(),5)));
        example.createCriteria().andDayDateBetween(DateUtils.getMonthBegin(DateUtils.getStrTime(DateUtils.getCurrentMonth())),DateUtils.getMonthEnd(DateUtils.getStrTime(DateUtils.getCurrentMonth())));
        List<ChildCourse> childCourses = childCourseMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(childCourses)){
            for(ChildCourse childCourse:childCourses){
                CourseChildExample courseChildExample = new CourseChildExample();
                courseChildExample.createCriteria().andCourseIdEqualTo(childCourse.getId());
                List<CourseChild> courseChildList = courseChildMapper.selectByExample(courseChildExample);
                if(!CollectionUtils.isEmpty(courseChildList)){
                    for(CourseChild courseChild:courseChildList){
                        courseChild.setCenterId(childCourse.getCenterId());
                        courseChild.setProjectType(childCourse.getProjectType());
                    }
                    courseChildren.addAll(courseChildList);
                }
            }
        }
        courseChildren = removeDuplicateChild(courseChildren);
        return courseChildren;
    }

    @Override
    public List<CourseChild> listGenPlanChild() {
        return this.childCourseMapper.listGenPlanChild();
    }

    @Override
    public List<ChildCourseVO> listByTeacherIdAndMonth(CourseChildListDTO courseChildListDTO) {
        if (courseChildListDTO.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
//        String dateDay = courseChildListDTO.getScheduleTime();
//        if(StringUtils.isEmpty(dateDay)){
//            dateDay = DateUtils.getDateYYYYMM();
//            courseChildListDTO.setScheduleTime(DateUtils.getDateYYYYMM());
//        }
//        String monthBegin = DateUtils.getMonthBegin(DateUtils.parseDate(dateDay));
//        String monthEnd = DateUtils.getMonthEnd(DateUtils.parseDate(dateDay));
//        courseChildListDTO.setMonthBegin(monthBegin);
//        courseChildListDTO.setMonthEnd(monthEnd);
        List<ChildCourseVO> childCourseVOS =  courseChildMapper.listByTeacherIdAndMonth(courseChildListDTO);
//        if(CollectionUtils.isEmpty(childCourseVOS)){
//            return childCourseVOS;
//        }

        //去除小孩ID和课程类型都相同的重复实体，因为已经生产一个月的项目
//        childCourseVOS = removeDuplicate(childCourseVOS);
//        for(ChildCourseVO childCourseVO:childCourseVOS){
//            if(isGenerateByTemp(courseChildListDTO.getCenterId(),childCourseVO.getChildId())) {
//                childCourseVO.setTemShowEdit((short) 1);
//            } else {
//                childCourseVO.setTemShowEdit((short) 0);
//                Date nowDate = DateUtils.getNowDate();
//                int day = DateUtils.differentDaysByMillisecond(nowDate, DateUtils.getMonthLastDay());
//                childCourseVO.setThreeDayBefore(day);
//                String curMonth = DateUtils.getDateYYYYMM();
//                //判断是否显示新生标准计划
//                EvaluateInfoDTO dto = this.childTrainingProgramService.getEvaluateInfo(childCourseVO.getChildId(),childCourseVO.getProjectType(),dateDay);
//                //获取项目确认时间
//                String confirmDate = this.childTrainingProgramService.getConfirmDate(childCourseVO.getChildId(),childCourseVO.getProjectType(),dateDay);
//                if (!StringUtils.isEmpty(curMonth) && !StringUtils.isEmpty(dateDay)) {
//                    //当月编辑下个月的项目，本月未确认也可编辑,当天确认当天可修改
//                    if (dto.getProgramCount()>0 &&(confirmDate == null|| DateUtils.getDate().equals(confirmDate) )) {
//                        childCourseVO.setIsShowEdit((short) 1);
//                    } else {
//                        childCourseVO.setIsShowEdit((short) 0);
//                    }
//                }
//                if(dto.getProgramCount()<=0 && childCourseVO.getIsShowEdit().equals((short)0)){
//                    //90天内无有效测评，显示新人标准计划
//                    if(dto.getEvaluateTime() ==null||DateUtils.differentDaysByMillisecond(dto.getEvaluateTime(),DateUtils.getNowDate())>90){
//                        childCourseVO.setIsNewProgram((short)1);
//                    }
//                }
//            }
//            if(childCourseVO.getLastConfirmTime() != null){
//                childCourseVO.setUpdateTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,childCourseVO.getLastConfirmTime()));
//            }
//        }
        return childCourseVOS;
    }

    //是否当月临时生成
    private boolean isGenerateByTemp(Long centerId,Long childId){
        if(centerId == null || childId == null){
            return false;
        }
        ChildTrainingProgramDTO childTrainingProgramDTO = new ChildTrainingProgramDTO();
        childTrainingProgramDTO.setCenterId(centerId);
        childTrainingProgramDTO.setChildId(childId);
        childTrainingProgramDTO.setTrainingProgramNumber(DateUtils.getDateYYYYMM());
        childTrainingProgramDTO.setTempGenerateDay(DateUtils.getDate());
        List<ChildTrainingProgram> childTrainingPrograms = childTrainingProgramService.list(childTrainingProgramDTO);
        if(!CollectionUtils.isEmpty(childTrainingPrograms)) {
            ChildTrainingProgram childTrainingProgram = childTrainingPrograms.get(0);
            String tmpGenarateDay = childTrainingProgram.getTempGenerateDay();
            String curDay = DateUtils.getDate();
            if(tmpGenarateDay.equals(curDay)){
                return true;
            }
        }
        return false;
    }

    @Override
    public List<ChildCourseVO> listReportChildren(CourseChildListDTO courseChildListDTO) {
        if (courseChildListDTO.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
        String dateDay = courseChildListDTO.getScheduleTime();
        if(StringUtils.isEmpty(dateDay)){
            dateDay = DateUtils.getDateYYYYMM();
        }
        String monthBegin = DateUtils.getMonthBegin(DateUtils.parseDate(dateDay));
        String monthEnd = DateUtils.getMonthEnd(DateUtils.parseDate(dateDay));
        courseChildListDTO.setMonthBegin(monthBegin);
        courseChildListDTO.setMonthEnd(monthEnd);
        List<ChildCourseVO> childCourseVOS =  courseChildMapper.listReportChildren(courseChildListDTO);
        if(CollectionUtils.isEmpty(childCourseVOS)){
            return childCourseVOS;
        }
        childCourseVOS = removeSameChild(childCourseVOS);
        return childCourseVOS;
    }

    private   List<ChildCourseVO>  removeDuplicate(List<ChildCourseVO> list)  {
        List<ChildCourseVO> tem  = new ArrayList<ChildCourseVO>();
        tem.addAll(list);
        for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {
            for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {
                if  (list.get(j).getChildId().equals(list.get(i).getChildId()) && list.get(j).getProjectType().equals(list.get(i).getProjectType()))  {
                    ChildCourseVO childCourseVO =  list.get(j);
                    tem.remove(childCourseVO);
                }
            }
        }
        return tem;
    }

    private  List<CourseChild>  removeDuplicateChild(List<CourseChild> list)  {
        List<CourseChild> tem  = new ArrayList<CourseChild>();
        tem.addAll(list);
        for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {
            for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {
                if  (list.get(j).getChildId().equals(list.get(i).getChildId()))  {
                    CourseChild courseChild =  list.get(j);
                    tem.remove(courseChild);
                }
            }
        }
        return tem;
    }

    private  List<ChildCourseVO>  removeSameChild(List<ChildCourseVO> list)  {
        List<ChildCourseVO> tem  = new ArrayList<ChildCourseVO>();
        tem.addAll(list);
        for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {
            for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {
                if  (list.get(j).getChildId().equals(list.get(i).getChildId()))  {
                    ChildCourseVO childCourseVO =  list.get(j);
                    tem.remove(childCourseVO);
                }
            }
        }
        return tem;
    }



    @Override
    public List<ChildCourseVO> list(CourseListDTO courseListDTO) {
        if (courseListDTO.getCenterId() == null) {
            throw new BusinessException("请选择中心。");
        }
        List<ChildCourseVO> childCourseVOS = new ArrayList<ChildCourseVO>();
        String dateDay = courseListDTO.getScheduleTime();
        if(StringUtils.isEmpty(courseListDTO.getScheduleTime())){
            dateDay = DateUtils.getDate();
        }

       /* ChildCourseExample example = new ChildCourseExample();
        ChildCourseExample.Criteria criteria = example.createCriteria();
        criteria.andDayDateEqualTo(dateDay).andCenterIdEqualTo(courseListDTO.getCenterId());
        if(courseListDTO.getTeacherId() != null){
            criteria.andTeacherIdEqualTo(courseListDTO.getTeacherId());
        }
        if(!StringUtils.isEmpty(courseListDTO.getTeacherName())){
            criteria.andTeacherNameEqualTo(courseListDTO.getTeacherName());
        }*/
        ChildCourseListDTO childCourseListDTO = new ChildCourseListDTO();
        childCourseListDTO.setCenterId(courseListDTO.getCenterId());
        childCourseListDTO.setDayDate(dateDay);
        if(courseListDTO.getTeacherId() != null){
            childCourseListDTO.setTeacherId(courseListDTO.getTeacherId());
        }
        if(!StringUtils.isEmpty(courseListDTO.getTeacherName())){
            childCourseListDTO.setTeacherName(courseListDTO.getTeacherName());
        }
        List<ChildCourse> childCourses =  childCourseMapper.list(childCourseListDTO);
        if(!CollectionUtils.isEmpty(childCourses)){
            Short isShowEdit = 1;
            String curDay = DateUtils.getDate();
            if(!curDay.equals(dateDay) ){
                isShowEdit = 0;
            }
            //是否当天
            Short isCurDay = 0;
            if(curDay.compareTo(dateDay)== 0){
                isCurDay = 1;
            }

            childCourseVOS.addAll(getChildCourseVOS(childCourses,courseListDTO,isShowEdit,isCurDay,courseListDTO.getChildName()));

        }
        return childCourseVOS;

    }

    @Override
    public String getTeacherName(CourseListDTO courseListDTO) {
        if(StringUtils.isEmpty(courseListDTO.getScheduleTime())){
            throw new BusinessException("时间为空");
        }
        if(courseListDTO.getChildId() == null){
            throw new BusinessException("小孩ID为空");
        }
        String dateDay = courseListDTO.getScheduleTime();
        String monthBegin = DateUtils.getMonthBegin(DateUtils.getStrTime(dateDay));
        String monthEnd = DateUtils.getMonthEnd(DateUtils.getStrTime(dateDay));
        ChildCourseExample example = new ChildCourseExample();
        ChildCourseExample.Criteria criteria = example.createCriteria();
        criteria.andCenterIdEqualTo(courseListDTO.getCenterId()).andDayDateBetween(monthBegin,monthEnd).andProjectTypeEqualTo(courseListDTO.getScheduleType());
        List<ChildCourse> childCourseList = childCourseMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(childCourseList)){
            return "";
        }
        else {
            for(ChildCourse childCourse:childCourseList){
                CourseChildExample courseChildExample = new CourseChildExample();
                courseChildExample.createCriteria().andCourseIdEqualTo(childCourse.getId());
                List<CourseChild> courseChildList = courseChildMapper.selectByExample(courseChildExample);
                if(!CollectionUtils.isEmpty(courseChildList)){
                   for(CourseChild courseChild:courseChildList){
                       if(courseChild.getChildId().equals(courseListDTO.getChildId())){
                           return childCourse.getTeacherName();
                       }
                   }
                }
            }

        }
        return "";
    }

    @Override
    public ChildCourseVO findById(Long id) {
        ChildCourseVO childCourseVO = new ChildCourseVO();
        ChildCourseExample childCourseExample = new ChildCourseExample();
        childCourseExample.createCriteria().andIdEqualTo(id);
        List<ChildCourse> childCourses = childCourseMapper.selectByExample(childCourseExample);
        if(!CollectionUtils.isEmpty(childCourses)){
            BeanUtils.copyProperties(childCourses.get(0),childCourseVO);
            CourseChildExample courseChildExample = new CourseChildExample();
            courseChildExample.createCriteria().andCourseIdEqualTo(childCourses.get(0).getId());
            List<CourseChild> courseChildList = courseChildMapper.selectByExample(courseChildExample);
            childCourseVO.setStudents(courseChildList);
            if(!StringUtils.isEmpty(childCourses.get(0).getDayDate())){
                childCourseVO.setScheduleTime(childCourses.get(0).getDayDate());
            }
            childCourseVO.setTeacherId(childCourses.get(0).getTeacherId());
            childCourseVO.setTeacherName(childCourses.get(0).getTeacherName());
            childCourseVO.setCourseId(childCourses.get(0).getId());
        }
        return childCourseVO;

    }

    private  List<ChildCourseVO> getChildCourseVOS(List<ChildCourse> childCourses, CourseListDTO courseListDTO,Short isShowEdit,Short isCurDay,String childName){
        List<ChildCourseVO> childCourseVOS = new ArrayList<ChildCourseVO>();
        for(ChildCourse childCourse:childCourses){
            boolean hasParamChildName = false;
            ChildCourseVO childCourseVO = new ChildCourseVO();
            BeanUtils.copyProperties(childCourse,childCourseVO);
            childCourseVO.setIsShowEdit(isShowEdit);
            childCourseVO.setIsCurDay(isCurDay);
            //查询切换日期或昨天是否录入过成绩
            Short isHaveData = 0;
            CourseChildListDTO courseChildListDTO = new CourseChildListDTO();
            courseChildListDTO.setCourseId(childCourse.getId());
            List<CourseChild> courseChildList = courseChildMapper.list(courseChildListDTO);
            if(!CollectionUtils.isEmpty(courseChildList)){
                for(CourseChild courseChild:courseChildList){
                    if(isCurDay == 1) {
                        //最近一次录入成绩的时间
                        TrainingProgramChildRecordListDTO trainingProgramChildRecordListDTO = new TrainingProgramChildRecordListDTO();
                        trainingProgramChildRecordListDTO.setCenterId(courseListDTO.getCenterId());
                        trainingProgramChildRecordListDTO.setTrainingProgramNumber(DateUtils.getDateYYYYMM());
                        trainingProgramChildRecordListDTO.setTrainingTime(courseListDTO.getScheduleTime());
                        trainingProgramChildRecordListDTO.setChildId(courseChild.getChildId());
                        trainingProgramChildRecordListDTO.setProjectType(childCourse.getProjectType());
                        trainingProgramChildRecordListDTO.setCheckTime((short)1);
                        String trainingTime = iTrainingProgramChildRecordService.getLastTrainingTime(trainingProgramChildRecordListDTO);
                        if(!StringUtils.isEmpty(trainingTime)){
                            isHaveData = 1;
                            break;
                        }
                    }
                    else{
                        TrainingProgramChildRecordListDTO trainingProgramChildRecordListDTO = new TrainingProgramChildRecordListDTO();
                        trainingProgramChildRecordListDTO.setCenterId(courseListDTO.getCenterId());
                        trainingProgramChildRecordListDTO.setTrainingTime(courseListDTO.getScheduleTime());
                        trainingProgramChildRecordListDTO.setCourseId(childCourse.getId());
                        trainingProgramChildRecordListDTO.setCheckTime((short)0);
                        String trainingTime = iTrainingProgramChildRecordService.getLastTrainingTime(trainingProgramChildRecordListDTO);
                        if(!StringUtils.isEmpty(trainingTime)){
                            isHaveData = 1;
                            break;
                        }
                    }
                }
                childCourseVO.setIsHaveData(isHaveData);
                List<String> childNames = new ArrayList<String>();
                for(CourseChild courseChild:courseChildList){
                    childNames.add(courseChild.getChildName());
                    if(!StringUtils.isEmpty(childName)){
                        if(!StringUtils.isEmpty(courseChild.getChildName()) && courseChild.getChildName().contains(childName)){
                            hasParamChildName =true;
                        }
                    }
                    //查看是否是新生标准计划
                    int newProgramCount = this.childTrainingProgramService.countNewProgram(courseChild.getChildId(),DateUtils.getDateYYYYMM(),childCourse.getProjectType());
                    if(newProgramCount>0 ){
                        childCourseVO.setIsShowEdit((short)0);
                    }
                }
                String names = StringUtils.join(childNames,",");
                childCourseVO.setChildren(names);
            }
            if(childCourse.getStartTime()!=null && childCourse.getEndTime()!=null){
                String courseTime = childCourse.getStartTime().substring(0,childCourse.getStartTime().length()-3)+"~"+childCourse.getEndTime().substring(0,childCourse.getEndTime().length()-3);
                childCourseVO.setCourseTime(courseTime);
            }
            if(StringUtils.isNotEmpty(childCourseVO.getChildren())) {
                childCourseVOS.add(childCourseVO);
            }
            else {
                if(hasParamChildName){
                    childCourseVOS.add(childCourseVO);
                }
            }
        }
        return childCourseVOS;
    }
}
